
// display
#include "Adafruit_GFX.h"
#include "Adafruit_GC9A01A.h"
#include "colors.h"
#include "SPI.h"
#define TFT1_DC 2
#define TFT1_CS 3
#define TFT2_DC 13
#define TFT2_CS 12
#define TFT_SDA 6
#define TFT_SCL 7
//SCL  -->  18
//SDA  -->  23

// Hardware SPI 
Adafruit_GC9A01A tft1(TFT1_CS, TFT1_DC); //upper glass
Adafruit_GC9A01A tft2(TFT2_CS, TFT2_DC); //lower glass

// RTC clock
#include "wire.h"
#include <RTClib.h>
RTC_DS3231 rtc;


int startx = 120, starty = 120; //center of display
int x, y, minute, hour;
int m, n, h;
double color = SAND1; // set sand color


void setup() {
  Serial.begin(115200);
  delay(2000);
  // 初始化I2C总线
  Wire.begin(8, 9); // SDA, SCL
  // setup RTC module
  Serial.println("1111111111111111111");
  if (! rtc.begin()) {
    Serial.println("Can't find RTC");
    Serial.flush();
    while (1);}
    // 如果RTC模块未设置时间，设置为编译时的时间
  if (rtc.lostPower()) {
    Serial.println("RTC lost power, setting the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  Serial.println("RTC initialized!");
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // 手动设置SPI引脚
  SPI.begin(TFT_SCL, -1, TFT_SDA, -1);
  // display setup
  tft1.begin();  
  tft2.begin(); 
  Serial.println("TFT begin");
  tft1.setRotation(2); 
  tft2.setRotation(2);
  tft1.fillScreen(COLOR0); 
  tft2.fillScreen(COLOR6);

 
  
  tft1.fillScreen(COLOR00);  // clear
  tft1.fillRect(0, 100, 240, 240, color); // full sand in glass 1
  tft2.fillScreen(COLOR0);  // no sand in glass 2
}
 
void loop() {

 Serial.println("make loop"); 
 for (h=8; h<=23; h++) {
   
  hour = h;
  minutes();
  delay(1000); // check time every second
 }


}


void minutes() {
    
  tft1.fillScreen(COLOR00);       // clear
  tft1.fillRect(0, 100, 240, 240, color); // full sand in glass 1
  tft2.fillScreen(COLOR0);        // no sand in glass 2

  tft1.setCursor(104, 10);
  tft1.setTextColor(COLOR4);
  tft1.setTextSize(4);
  if (hour<10){
    tft1.print("0");
  }
  tft1.println(hour);

     //animated sand track
   for (int i = 0; i<250; i+=10) {
    tft2.fillRect(118, 0, 5, i, color);
    delay(10);
   }


  tft1.fillCircle(30, 30, 30, GREY1); tft2.fillCircle(30, 30, 30, GREY1); // add reflections
// trickling sand
   
   m = map(minute, 0, 59, 0, 141);
   for (m=0; m<141; m++){
     tft1.fillTriangle(0, m*0.9+68, 240, m*0.9+68, 120, m*1.2+90, COLOR0);     //upper glass

     n= map(m, 0, 141, 250, 75);
     tft2.fillTriangle(0, n*0.55+105, 240, n*0.55+105, 120, n, color);  //lower glass
     tft2.fillTriangle(108, n+7, 132, n+7, 120, n-6, color);  //sand track end

     delay(50);
   }
   tft2.fillRect(118, 0, 5, n-4, COLOR00); //delete sand track
}


 